package com.simple.utils;

import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class RedisUtils{
	
	private static final Logger logger = LoggerFactory.getLogger(RedisUtils.class);
	
	@Autowired
	public RedisTemplate<Object,Object> redisTemplate;
	
	//字符串设置
	public void setValue(String key,Object value) {
		if(getConnection()) {
			redisTemplate.opsForValue().set(key, value);
		}
	}
	//设置三十分钟时长
	public void setSessionString (String key,String value,long time) {
		redisTemplate.opsForValue().set(key,value,30,TimeUnit.MINUTES);
	}
	//获取value
	public Object getString(String key) {
		return (getConnection())?redisTemplate.opsForValue().get(key):"";
	}
	//删除key
	public boolean delete(String key) {
		return (getConnection())?redisTemplate.delete(key):false;
	}
	//批量删除
	public void batchDelete(String patternKeys) {
		redisTemplate.delete(redisTemplate.keys(patternKeys));
	}
	public boolean getConnection() {
		try {
			redisTemplate.getConnectionFactory().getConnection();
		} catch (Exception e) {
			logger.error("redis连接异常"+e);
			return false;
		}
		return true;
	}
	
	
}
